var sessionTimeOut;

/**
 * 判断List是否为空.added by baishuang402,on 20161114
 */
function listIsNull(paraList) {
	if (null == paraList || '' == paraList || paraList.length == 0)
		return true;
	else
		return false;
}

function isNull(para) {
	if (null == para || '' == para || undefined == para || typeof (para) == "undefined")
		return true;
	else
		return false;
}

function getCurrentDateTime() {
	var curr_time = new Date();
	var strDate = curr_time.getFullYear() + "-";
	strDate += curr_time.getMonth() + 1 + "-";
	strDate += curr_time.getDate() + " ";
	strDate += curr_time.getHours() + ":";
	strDate += curr_time.getMinutes() + ":";
	strDate += curr_time.getSeconds();
	return strDate;
}

function getCurrentDateTime2() {
	var curr_time = new Date();
	var strDate = curr_time.getFullYear() + "-";
	var month = curr_time.getMonth() + 1;
	var day = curr_time.getDate();
	if (month < 10) {
		month = "0" + month;
	}
	if (day < 10) {
		day = "0" + day;
	}
	strDate += month + "-";
	strDate += day + "-";
	strDate += curr_time.getHours() + ":";
	strDate += curr_time.getMinutes() + ":";
	strDate += curr_time.getSeconds();
	return strDate;
}

function getCurrentDate() {
	var curr_time = new Date();
	var strDate = curr_time.getFullYear() + "-";
	var tmpMon = curr_time.getMonth() + 1;
	if (tmpMon < 10) {
		tmpMon = "0" + tmpMon;
	}
	strDate += tmpMon + "-";
	var tmpDate = curr_time.getDate();
	if (tmpDate < 10) {
		tmpDate = "0" + tmpDate;
	}
	strDate += tmpDate;
	return strDate;
}

/**
 * 去除日期分隔符，yyyy-mm-dd -> yyyymmdd
 * 
 * @param StrDate
 * @returns
 */
function formateDateToNoSplitFlag(StrDate) {
	StrDate = StrDate.replace(/\-/g, "");
	return StrDate;
}

function myformatter(date) {
	var y = date.getFullYear();
	var m = date.getMonth() + 1;
	var d = date.getDate();
	return y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d);
}

// 截取日期前10位 yyyy-MM-dd
function formatDt(value) {
	if (value != null && value != '' && value.length > 10) {
		return value.substr(0, 10);
	} else {
		return value;
	}
}

function myparser(s) {
	if (!s)
		return new Date();
	var ss = (s.split('-'));
	var y = parseInt(ss[0], 10);
	var m = parseInt(ss[1], 10);
	var d = parseInt(ss[2], 10);
	if (!isNaN(y) && !isNaN(m) && !isNaN(d)) {
		return new Date(y, m - 1, d);
	} else {
		return new Date();
	}
}
/**
 * 时间戳转为为YYYY-MM-dd格式
 * 
 * @param now
 * @returns {String}
 */
function formatStampDate(str) {
	if (vaildNotNull(str)) {
		var d = new Date(str);
		var year = d.getFullYear();
		var month = d.getMonth() + 1;
		var date = d.getDate();
		var hour = d.getHours();
		var minute = d.getMinutes();
		var second = d.getSeconds();
		return year + "-" + (month < 10 ? ('0' + month) : month) + "-" + (date < 10 ? ('0' + date) : date);// +"
		// "+hour+":"+minute+":"+second;
	} else {
		return "";
	}
}
function paramString2obj(serializedParams) {

	var obj = {};
	function evalThem(str) {
		var attributeName = str.split("=")[0];
		var attributeValue = str.split("=")[1];
		if (attributeValue != null && attributeValue != "null" && attributeValue != "") {
			attributeValue = attributeValue.replace(/(\s*$)/g, "");
		}
		if (!attributeValue) {
			return;
		}

		var array = attributeName.split(".");
		for (var i = 1; i < array.length; i++) {
			var tmpArray = Array();
			tmpArray.push("obj");
			for (var j = 0; j < i; j++) {
				tmpArray.push(array[j]);
			}
			var evalString = tmpArray.join(".");
			// alert(evalString);
			if (!eval(evalString)) {
				eval(evalString + "={};");
			}
		}

		eval("obj." + attributeName + "='" + attributeValue + "';");

	}

	var properties = serializedParams.split("&");
	for (var i = 0; i < properties.length; i++) {
		evalThem(properties[i]);
	}

	return obj;
}

$.fn.form2json = function() {
	var serializedParams = this.serialize();
	serializedParams = serializedParams.replace(/\+/g, " "); // g表示对整个字符串中符合条件的都进行替换
	serializedParams = decodeURIComponent(serializedParams, true);
	var obj = paramString2obj(serializedParams);
	return obj;
}

function createAjaxFail(msg) {
	var obj = new Object();
	var syshead = new Object();
	var ret = new Object();
	ret.CODE = "999999";
	ret.DESC = msg;
	var RET_ARR = new Array(1);
	RET_ARR[0] = ret;
	syshead.RET_ARR = RET_ARR;
	obj.RET_HEAD = syshead;
	return obj;
}

/**
 * 检查登录是否超时
 */
function checkTimeOut() {
	$.ajaxSetup({
		complete : function(XMLHttpRequest, textStatus) {
			var sessionStatus = XMLHttpRequest.getResponseHeader("sessionStatus"); // 通过XMLHttpRequest取得响应头,sessionstatus
			sessionTimeOut = sessionStatus;
		}
	});
	return sessionTimeOut;
}

function AjaxJsonAsync(data) {

	if (checkTimeOut() == 'timeout') {
		QEX.confirm({
			title : "提示",
			message : "登录超时，请重新登录！"
		}).on(function(r) {
			if (r) {
				// window.location.href = baseUrl + 'login.jsp'; // 跳转到登陆页面
				window.location.href = casUrl + '/logout?service=' + newUrl;
				// return false;
			}
		});
		return false;
	}

	if (data == null || data == 'undefined' || data == "") {
		return createAjaxFail("错误的请求参数");
	}
	var jsonData = JSON.stringify(data);
	var res = "";
	$.ajax({
		type : "POST",
		async : false,
		url : baseUrl + "driverAction.do",
		data : jsonData,
		dataType : "json",
		success : function(result) {

			res = result;
		},
		error : function(result) {
			return createAjaxFail("执行异常，请联系管理员");
		}
	});

	return res;
}

function RemoteAjaxJsonAsync(data) {

	if (checkTimeOut() == 'timeout') {
		QEX.confirm({
			title : "提示",
			message : "登录超时，请重新登录！"
		}).on(function(r) {
			if (r) {
				// window.location.href = baseUrl + 'login.jsp'; // 跳转到登陆页面
				window.location.href = casUrl + '/logout?service=' + newUrl;
				// return false;
			}
		});
		return false;
	}

	if (data == null || data == 'undefined' || data == "") {
		return createAjaxFail("错误的请求参数");
	}
	data.remoteServiceId = data.serviceId;
	data.serviceId = "remoteService";
	var jsonData = JSON.stringify(data);
	var res = "";
	$.ajax({
		type : "POST",
		async : false,
		url : baseUrl + "driverAction.do",
		data : jsonData,
		dataType : "json",
		success : function(result) {

			res = result;
		},
		error : function(result) {
			return createAjaxFail("执行异常，请联系管理员");
		}
	});

	return res;
}

function setJson2Form(formid, jsonBody) {
	var formObj = $("#" + formid);
	for ( var x in jsonBody) {
		try {

			var elementObj = formObj.find("input[id=" + x + "]");
			if (elementObj.length > 0) {
				var elementType = elementObj.attr("type");

				if (elementType == "text") {
					elementObj.val(jsonBody[x]);
				} else if (elementType == "radio") {
					elementObj.val([ jsonBody[x] ]);
				} else if (elementType == "password") {
					// console.info('ccccc:' + x);
				} else if (elementType = "hidden") {
					// 处理numberbox分支
					elementObj = formObj.find("input[numberboxname=" + x + "]");
					if (elementObj.length > 0) {
						elementObj.numberbox('setValue', jsonBody[x]);
						// elementObj.val(jsonBody[x]);
					}
				} else {
					// console.info('找不到元素:' + x);
				}
			} else {
				// console.info('找不到元素:' + x);
			}

		} catch (e) {
			// console.info(e);
		}
	}

};

(function($) {
	$.fn.datepicker.dates['zh-CN'] = {
		days : [ "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日" ],
		daysShort : [ "周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日" ],
		daysMin : [ "日", "一", "二", "三", "四", "五", "六", "日" ],
		months : [ "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月" ],
		monthsShort : [ "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月" ],
		today : "今天",
		suffix : [],
		meridiem : [ "上午", "下午" ]
	};
}(jQuery));

function accAdd(arg1, arg2) {
	var r1, r2, m;
	try {
		r1 = arg1.toString().split(".")[1].length;
	} catch (e) {
		r1 = 0;
	}
	try {
		r2 = arg2.toString().split(".")[1].length;
	} catch (e) {
		r2 = 0;
	}
	m = Math.pow(10, Math.max(r1, r2));
	return (arg1 * m + arg2 * m) / m;
}

// 减法函数
function Subtr(arg1, arg2) {
	var r1, r2, m, n;
	try {
		r1 = arg1.toString().split(".")[1].length;
	} catch (e) {
		r1 = 0;
	}
	try {
		r2 = arg2.toString().split(".")[1].length;
	} catch (e) {
		r2 = 0;
	}
	m = Math.pow(10, Math.max(r1, r2));
	// last modify by deeka
	// 动态控制精度长度
	n = (r1 >= r2) ? r1 : r2;
	return ((arg1 * m - arg2 * m) / m).toFixed(n);
}

// 乘法函数
function accMul(arg1, arg2) {
	var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
	try {
		m += s1.split(".")[1].length;
	} catch (e) {
	}
	try {
		m += s2.split(".")[1].length;
	} catch (e) {
	}
	return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}

// 除法函数
function accDiv(arg1, arg2) {
	var t1 = 0, t2 = 0, r1, r2;
	try {
		t1 = arg1.toString().split(".")[1].length;
	} catch (e) {
	}
	try {
		t2 = arg2.toString().split(".")[1].length;
	} catch (e) {
	}
	with (Math) {
		r1 = Number(arg1.toString().replace(".", ""));
		r2 = Number(arg2.toString().replace(".", ""));
		return (r1 / r2) * pow(10, t2 - t1);
	}
}

function bindEnterKey(ids) {
	for (var i = 0; i < ids.length; i++) {
		$("#" + ids[i]).bind("keyup", function(e) {
			if (e.which == 13) { // Enter key
				e.preventDefault(); // to skip default behaviour of enter key
				var index = 0;
				for (var j = 0; j < ids.length; j++) {
					if (this.id == ids[j]) {
						index = j;
						break;
					}
				}
				if (index < ids.length - 1) {
					var nextinput = $("#" + ids[index + 1]);
					if (nextinput != undefined) {
						nextinput.focus();
					} else {
						null;
					}
				} else {
					null;
				}
			}
		});
	}
}

// 权限校验 需要传入funcCode
function checkAuth(funcCode) {
	var reqData = new Object();
	reqData.serviceId = "mpRoleService";
	reqData.flag = "10";
	reqData.funcCode = funcCode;
	var res = AjaxJsonAsync(reqData);
	if (res != "") {
		if (!res.success) {
			QEX.alert({
				title : "消息提示",
				message : res.msg
			});
			// toastr.error(res.msg, "提示");
			return false;
		}
		return true;
	}
}

/*
 * 获取业务参数 add by heqqiongqiong600
 */
function getParameterService03(parentParaCode, paraType) {
	var reqData = new Object();
	reqData.serviceId = "mpParameterService";
	reqData.flag = "03";
	reqData.parentParaCode = parentParaCode;// 业务类型
	reqData.paraType = paraType;// 参数父级类型
	var res = AjaxJsonAsync(reqData);
	return res;
}

/*
 * 通过省的编码获取省的名称 add by heqqiongqiong600
 */
function getAreaNameByCode(areaCode) {
	var areaName = "";
	if (areaCode != null && areaCode != "") {
		var reqData = new Object();
		reqData.serviceId = "paAreaService";
		reqData.flag = "02";
		reqData.areaCode = areaCode;
		var res = AjaxJsonAsync(reqData);
		if (res != null && res != "" && res != undefined && res[0] != null && res[0] != "" && res[0] != undefined) {
			areaName = res[0].areaName;
		}
	}
	return areaName;
}

/*
 * 通过市的编码获取市的名称 add by heqqiongqiong600
 */
function getCityNameByCode(cityCode) {
	var cityName = "";
	if (cityCode != null && cityCode != "") {
		var reqData = new Object();
		reqData.serviceId = "paAreaService";
		reqData.flag = "05";
		reqData.cityCode = cityCode;
		var res = AjaxJsonAsync(reqData);
		if (res != null && res != "" && res != undefined && res.cityName != null && res.cityName != ""
				&& res.cityName != undefined) {
			cityName = res.cityName;
		}
	}
	return cityName;
}

/*
 * 获取会员系统所有功能菜单 add by fanshuhuan
 */
function getMmFunc() {
	var reqData = new Object();
	reqData.serviceId = "mpFuncService";
	reqData.flag = "01";
	var res = AjaxJsonAsync(reqData);
	return res.jsonarray;
}

function getFuncName(value, mmFuncCodeList) {
	for (var i = 0; i < mmFuncCodeList.length; i++) {
		if (value == mmFuncCodeList[i].funcCode) {
			return mmFuncCodeList[i].funcName;
		}
	}
	return value;
}

/*
 * 获取使用浏览器版本 add by zhouchengxiang600
 */
function getMyBrowser() {
	var userAgent = navigator.userAgent; // 取得浏览器的userAgent字符串
	var isOpera = userAgent.indexOf("Opera") > -1;
	if (isOpera) {
		return "Opera";
	} else if (userAgent.indexOf("Firefox") > -1) {
		return "FF";
	} else if (userAgent.indexOf("Chrome") > -1) {
		return "Chrome";
	} else if (userAgent.indexOf("Safari") > -1) {
		return "Safari";
	} else if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) {
		return "IE";
	}
}

/**
 * 根据会员号和业务类型判断营业时间和黑名单
 */
function checkAuthBy070031(memberNo, busiType) {
	var reqData = new Object();
	reqData.remoteServiceId = "070031";
	reqData.serviceId = "remoteService";
	reqData.memberNo = memberNo;
	reqData.busiType = busiType;
	var res = AjaxJsonAsync(reqData);
	if ("" != res) {
		if (!res.success) {
			QEX.alert({
				title : "消息提示",
				message : res.msg
			});
			return false;
		}
		return true;
	}
}

/**
 * 根据会员号和业务类型判断营业时间和黑名单
 */
function checkPaymentBy070031(memberNo, busiType) {
	var reqData = new Object();
	reqData.remoteServiceId = "070031";
	reqData.serviceId = "remoteService";
	reqData.memberNo = memberNo;
	reqData.busiType = busiType;
	var res = AjaxJsonAsync(reqData);
	return res;
}

/**
 * dataGrid 显示下拉选项循环方法
 */
function dropDownOptionLoop(userList, value) {
	for (var i = 0; i < userList.length; i++) {
		if (value == userList[i].paraCode) {
			return userList[i].paraDesc;
		}
	}
	return value;
}

// grid日期格式化 add by heqq
function formatterJsonTime2String(timeStamp) {
	if (timeStamp == null || timeStamp == "" || timeStamp == "undefined") {
		return "";
	}
	var a = timeStamp.substring(0, 10);
	return a;
}
/**
 * 业务类型数据格式化 add by heqq
 */
function formatterParamList(value, rec, paramList) {
	for (var i = 0; i < paramList.length; i++) {
		if (value == paramList[i].paraCode) {
			return paramList[i].paraDesc;
		}
	}
	return value;
}
/**
 * 业务类型数据格式化 add by baishuang
 */
function formatParamList(value, paramList) {
	for (var i = 0; i < paramList.length; i++) {
		if (value == paramList[i].paraCode) {
			return paramList[i].paraDesc;
		}
	}
	return value;
}
/**
 * 根据机构code获取名称 add by heqq
 */
function formatterOrgNameByCode(value, rec) {
	var reqData = new Object();
	reqData.serviceId = "mpOrgService";
	reqData.flag = "12";
	reqData.orgCode = value;
	var res = AjaxJsonAsync(reqData);
	if (res.length == 1) {
		return res[0].orgName;
	} else {
		return value;
	}
}

/**
 * 下拉框格式化 add by heqq
 */
function formatterSelectControl(dataList, controlIdStr) {
	$(controlIdStr).append("<option value=''></option>");
	for (var i = 0; i < dataList.length; i++) {
		$(controlIdStr).append("<option value=" + dataList[i].paraCode + ">" + dataList[i].paraDesc + "</option>");
	}
}

/**
 * 无空白值下拉框格式化 add by fanshuhuan
 */
function formatterSelectControlWithoutBlank(dataList, controlIdStr) {
	for (var i = 0; i < dataList.length; i++) {
		$(controlIdStr).append("<option value=" + dataList[i].paraCode + ">" + dataList[i].paraDesc + "</option>");
	}
}

/**
 * 多选框格式化 add by fanshuhuan
 */
function formatterCheckbox(dataList, id, controlIdStr) {
	for (var i = 0; i < dataList.length; i++) {
		$(controlIdStr).append(
				"<label class='checkbox-inline'><input type='checkbox' id='" + id + i + "' name="
						+ controlIdStr.substring(1) + " value=" + dataList[i].paraCode + "><span>"
						+ dataList[i].paraDesc + "</span></label>");
	}
}

/**
 * 业务类型数据格式化(多个值用“,”分割时的转换) add by heqq
 */
function formatterMultiParamList(value, splitStr, paramList) {
	if (value != null && value != "" && value != undefined) {
		var strs = value.split(","); // 字符分割
		var result = "";
		// 把分割出的每个字符转义出来
		for (i = 0; i < strs.length; i++) {
			var valueStr = strs[i];
			// 从业务参数列表中取出转义字符
			for (var r = 0; r < paramList.length; r++) {
				if (valueStr == paramList[r].paraCode) {
					if (i == 0) {
						result = paramList[r].paraDesc;
					} else {
						result = result + "," + paramList[r].paraDesc;
					}
				}
			}
		}
		return result;
	} else {
		return "";
	}
}

/*
 * 根据OrgAreaCode获取市区的名称 add by heqqiongqiong600
 */
function getCityNameByOrgAreaCode(orgAreaCode) {
	var cityName = "";
	if (orgAreaCode != null && orgAreaCode != "") {
		var reqData = new Object();
		reqData.serviceId = "070011"; // 服务id
		reqData.findType = "B";
		reqData.cityType = "2";
		reqData.oraAreaCode = orgAreaCode;
		var res = RemoteAjaxJsonAsync(reqData);
		if (res != null && res != "" && res != undefined) {
			var cityObj = res.jsonBody.queryList;
			if (cityObj != null && cityObj != "" && cityObj != undefined) {
				var nameStr = cityObj[0].cityName;
				if (nameStr != null && nameStr != "" && nameStr != undefined) {
					cityName = nameStr;
				}
			}
		}
	}
	return cityName;
}

function AjaxJson(data, callback, async) {

	if (data == null || data == 'undefined' || data == "") {
		return createAjaxFail("错误的请求参数");
	}
	var jsonData = JSON.stringify(data);
	$.ajax({
		type : "POST",
		async : async,
		url : baseUrl + "driverAction.do",
		data : jsonData,
		dataType : "json",
		timeout : 3500,
		success : function(result) {
			if (result.retCode == "0000") {
				callback(result);
			} else {
				QEX.alert({
					title : "提醒",
					message : result.msg
				});
			}
		},
		error : function(result) {
			if (result == undefined || result == null || result.status == 0) {
				QEX.alert({
					title : "提醒",
					message : "连接超时！"
				});
				return;
			} else {
				QEX.alert({
					title : "提醒",
					message : "网络异常" + result.status + "   " + result.statusText
				});
				return;
			}
		}
	});
}

/*
 * 验证不为空 add by heqqiongqiong600
 */
function vaildNotNull(obj) {
	if (obj != null && obj != "" && obj != undefined && obj != "null" && obj != "undefined") {
		return true;
	}
	return false;
}
/*
 * 关闭弹出框 add by heqqiongqiong600
 */
function closePage(modalId) {
	$("#" + modalId).modal('hide');
}

/*
 * 格式化金额
 * 
 */
function formatMoney(s, type) {
	if (/(\-|\+)[^0-9\.]/.test(s))
		return "0.00";
	if (s == null || s == "")
		return "0.00";

	var prefix = "";
	// s = s/10000;
	if (s >= 1000 || s <= -1000) {
		if (s <= -1000) {
			prefix = "-";
			s = s.toString().substring(1);
		}
		s = s.toString().replace(/^(\d*)$/, "$1.");
		s = (s + "00").replace(/(\d*\.\d\d)\d*/, "$1");
		s = s.replace(".", ",");
		var re = /(\d)(\d{3},)/;
		while (re.test(s)) {
			s = s.replace(re, "$1,$2");
		}
		s = s.replace(/,(\d\d)$/, ".$1");
		if (type == 1) {
			var a = s.split(".");
			if (a[1] == "00") {
				s = a[0];
			}
		}
	} else {
		s = s.toString().replace(/^(\d*)$/, "$1.");
		s = (s + "00").replace(/(\d*\.\d\d)\d*/, "$1");
	}
	return prefix + s;
}

function codeToDesc(codeList, limite, dirbook, otherName) {
	if (codeList == null || codeList == 'undefined' || codeList == "")
		return "-";
	if (dirbook == null || dirbook == 'undefined' || dirbook == "" || dirbook.length == 0)
		return codeList;
	// if(codeList.indexOf(limite)==-1)return codeList;
	var codes = codeList.split(limite);
	var result = [];
	for (var i = codes.length - 1; i >= 0; i--) {
		var find = false;
		for (var j = dirbook.length - 1; j >= 0; j--) {
			if (dirbook[j].paraCode == codes[i]) {
				result.push(dirbook[j].paraDesc);
				find = true;
				break;
			}
		}
		var tcode = codes[i];

		if (!find) {
			if (!otherName) {
				result.push(tcode);
			} else {
				result.push(otherName);
			}
		}

	}
	return result.join(limite);
}

/**
 * 获得焦点去掉千分位展示
 * 
 * @param obj
 */
function formatAmountOnFocus(obj) {
	var value = $(obj).val();
	$(obj).val(value.replace(/,/g, ""));
}

/**
 * 失去焦点进行千分位展示保留小数位
 * 
 * @param obj
 */
function formatAmountOnBlurbeforePoint(obj) {
	var value = $(obj).val();
	if (!isSpace(value)) {
		value = value.replace(/,/g, "");
		if (!isNaN(value)) {
			// value=parseFloat(value);
			$(obj).val(formatMoneybeforePoint(value));
		}
	}
}
/**
 * 失去焦点进行千分位展示 不显示数字大写转化
 * 
 * @param obj
 */
function formatAmountCountOnBlurNotCast(obj) {
	var value = $(obj).val();
	$(obj).val(datagridFormatNumber(value));
}
/**
 * 失去焦点进行千分位展示
 * 
 * @param obj
 */
function formatAmountOnBlur(obj) {
	var value = $(obj).val();
	if (!value) {
		value = 0;
	}
	value = removalComma(value);
	$(obj).val(datagridFormatNumber(value));
	var chn = chineseNumber(value);
	if (!isSpace(chn)) {
		$(obj).parent().append('<div class="span_phone_code" id=' + obj.id + 1 + '></div>');
		var $item = $("#" + obj.id + 1);
		$item.text(chn);
		$item.css({
			'width' : chn.length * 12,
			'margin-left' : $(obj).parent().find('.control-label').width() + 5,
			'width' : chn.length * 14 + 20,
			'margin-left' : $(obj).parent().find('.control-label').width() + 5,
			'padding' : '0px 10px',
			'background' : '#fff3eb none no-repeat 10px center',
			'line-height' : '35px',
			'margin-top' : '10px',
			'text-align' : 'center',
			'font-size' : '12px',
			'display' : 'block'
		})
	} else {
		var $item = $("#" + obj.id + 1);
		$item.css({
			'display' : 'none'
		})
	}
}

function formatAmountOnBlurGe(obj) {
	var value = $(obj).val();
	value = $.trim(value);
	value=value.replace(/[-|+]/g, '');
	$(obj).val(datagridFormatNumber(value));
	var chn = chineseNumber(value);
	if (!isSpace(chn)) {
		$(obj).siblings("div[id='"+obj.id+1+"']").remove();
		$(obj).parent().append('<div class="span_phone_code" id=' + obj.id + 1 + '></div>');
		var $item = $("#" + obj.id + 1);
		$item.text(chn);
		$item.css({
			'width' : chn.length * 12,
			'margin-left' : $(obj).parent().find('.control-label').width() + 5,
			'width' : chn.length * 14 + 20,
			'margin-left' : $(obj).parent().find('.control-label').width() + 5,
			'padding' : '0px 10px',
			'background' : '#fff3eb none no-repeat 10px center',
			'line-height' : '35px',
			'margin-top' : '10px',
			'text-align' : 'center',
			'font-size' : '12px'
		})
	} else {
		var $item = $("#" + obj.id + 1);
		$item.css({
			'display' : 'none'
		})
	}

}

/**
 * 去除逗号，转换为千分位后含有逗号，如果再次点击输入框，则再次执行格式化千分位操作，则不能识别逗号，需要先去除 并四舍五入保留2位小数
 * 
 * @add by RENJIE
 * @add time 2016-9-5
 * @param value
 */
function removalComma(value) {
	var temp = value;
	if (value) {
		if (value.indexOf(",")) {
			temp = value.replace(/,/g, "");
		}
	}
	return parseFloat(temp).toFixed(2);
}

/**
 * 失去焦点进行千分位展示 不显示数字大写转化 数据不显示小数位
 * 
 * @param obj
 */
function formatAmountOnBlurNotCast(obj) {
	var value = $(obj).val();
	$(obj).val(castFormatNumber(value));
}
function formatAmountSetValue(obj) {
	var value = $(obj).val();
	$(obj).val(datagridFormatNumber(value));
	var chn = chineseNumber(value);
	if (!isSpace(chn)) {
		$(obj).parent().append('<div class="span_phone_code" id=' + obj.attr("id") + 1 + '></div>');
		var $item = $("#" + obj.attr("id") + 1);
		$item.text(chn);
		$item.css({
			'width' : chn.length * 12,
			'margin-left' : $(obj).parent().find('.control-label').width() + 5,
			'width' : chn.length * 14 + 20,
			'margin-left' : $(obj).parent().find('.control-label').width() + 5,
			'padding' : '0px 10px',
			'background' : '#fff3eb none no-repeat 10px center',
			'line-height' : '35px',
			'margin-top' : '10px',
			'text-align' : 'center',
			'font-size' : '12px'
		})
	} else {
		var $item = $("#" + obj.attr("id") + 1);
		$item.css({
			'display' : 'none'
		})
	}

}
function formatMoneybeforePoint(num) {
	if (/(\-|\+)[^0-9\.]/.test(num))
		return "0.00";
	if (num == null || num == "")
		return "0.00";
	var a = num.split(".");
	if (a.length > 1 && (a[1] != "" || a[1] != null)) {
		return (a[0] + '').replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,') + "." + a[1];
	} else {
		s = a[0];
		s = s.toString().replace(/^(\d*)$/, "$1.");
		s = (s + "00").replace(/(\d*\.\d\d)\d*/, "$1");
		return (s + '').replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,')
	}
	// alert((a[0] + '').replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g,
	// '$&,')+"."+a[1]);

}
// 判断是否为空
function isSpace(val) {
	if ($.trim(val).length > 0)
		return false;
	else
		return true;
}

function getCityNameByCityCode(cityCode) {
	var cityName = "";
	if (cityCode != null && cityCode != "") {
		var reqData = new Object();
		reqData.serviceId = "070011"; // 服务id
		reqData.findType = "B";

		reqData.cityCode = cityCode;
		var res = RemoteAjaxJsonAsync(reqData);
		if (res != null && res != "" && res != undefined) {
			var cityObj = res.jsonBody.queryList;
			if (cityObj != null && cityObj != "" && cityObj != undefined) {
				var nameStr = cityObj[0].cityName;
				if (nameStr != null && nameStr != "" && nameStr != undefined) {
					cityName = nameStr;
				}
			}
		}
	}
	return cityName;
}
// enter 键监听查询事件 add by heqq
function enterKeyToQuery(idArr, queryId) {
	document.onkeydown = function() {
		var evt = window.event || arguments[0];
		if (evt && evt.keyCode == 13) {
			return false;
		}
	}
	for (var i = 0; i < idArr.length; i++) {
		if (vaildNotNull(idArr[i])) {
			$('#' + idArr[i]).bind('keyup', function(event) {
				if (event.keyCode == "13") {
					// 回车执行查询
					$('#' + queryId).click();
				}
			});
		}
	}
}

// 金额数字转中文大写
function chineseNumber(num) {

	if (isNaN(num) || num == 0 || num > Math.pow(10, 13))
		return "";
	num = num.toString().replace(/,/g, "");
	var cn = "零壹贰叁肆伍陆柒捌玖";
	var unit = new Array("拾佰仟", "分角");
	var unit1 = new Array("万亿", "");
	var numArray = num.toString().split(".");
	var start = new Array(numArray[0].length - 1, 2);
	var flag = false;
	/*if (numArray[0].length == 13) {
		flag = true;
	}*/
	//修改拾万亿的时候，显示拾亿的问题 add by ranmenglong158 2017-01-03
	if (numArray[0].length >= 13) {
		flag = true;
	}
	if (numArray.length == 2) {
		if (numArray[1].length > 2) {
			return "";
		}
	}
	function toChinese(num, index) {
		var num = num.replace(/\d/g, function($1) {
			return cn.charAt($1) + unit[index].charAt(start-- % 4 ? start % 4 : -1)
		})
		return num
	}
	for (var i = 0; i < numArray.length; i++) {
		var tmp = ""
		for (var j = 0; j * 4 < numArray[i].length; j++) {
			var strIndex = numArray[i].length - (j + 1) * 4
			var str = numArray[i].substring(strIndex, strIndex + 4)
			var start = i ? 2 : str.length - 1
			var tmp1 = toChinese(str, i)
			tmp1 = tmp1.replace(/(零.)+/g, "零").replace(/零+$/, "")
			tmp1 = tmp1.replace(/^壹拾/, "拾")
			tmp = (tmp1 + unit1[i].charAt(j - 1)) + tmp
		}
		var idx = tmp.indexOf("亿");
		if (idx > 0) {
			var char = tmp.charAt(idx + 1);
			if (char == "万") {
				tmp = tmp.substring(0, idx + 1) + tmp.substring(idx + 2);
			}
		}
		numArray[i] = tmp
	}

	numArray[1] = numArray[1] ? numArray[1] : ""
	numArray[0] = numArray[0] ? numArray[0] + "元" : numArray[0], numArray[1] = numArray[1].replace(/^零+/, "")
	numArray[1] = numArray[1].match(/分/) ? numArray[1] : numArray[1] + "整"
	if (flag) {
		numArray[0] = numArray[0].substring(0, 1) + "万" + numArray[0].substring(1);
	}
	return numArray[0] + numArray[1]
}

/**
 * 身份证校验
 * 
 * @param code
 * @returns {Boolean}
 */
function IdentityCodeValid(code) {
	var city = {
		11 : "北京",
		12 : "天津",
		13 : "河北",
		14 : "山西",
		15 : "内蒙古",
		21 : "辽宁",
		22 : "吉林",
		23 : "黑龙江 ",
		31 : "上海",
		32 : "江苏",
		33 : "浙江",
		34 : "安徽",
		35 : "福建",
		36 : "江西",
		37 : "山东",
		41 : "河南",
		42 : "湖北 ",
		43 : "湖南",
		44 : "广东",
		45 : "广西",
		46 : "海南",
		50 : "重庆",
		51 : "四川",
		52 : "贵州",
		53 : "云南",
		54 : "西藏 ",
		61 : "陕西",
		62 : "甘肃",
		63 : "青海",
		64 : "宁夏",
		65 : "新疆",
		71 : "台湾",
		81 : "香港",
		82 : "澳门",
		91 : "国外 "
	};
	var tip = "";
	var pass = true;

	if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
		tip = "身份证号格式错误";
		pass = false;
	}

	else if (!city[code.substr(0, 2)]) {
		tip = "地址编码错误";
		pass = false;
	} else {
		// 18位身份证需要验证最后一位校验位
		if (code.length == 18) {
			code = code.split('');
			// ∑(ai×Wi)(mod 11)
			// 加权因子
			var factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
			// 校验位
			var parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
			var sum = 0;
			var ai = 0;
			var wi = 0;
			for (var i = 0; i < 17; i++) {
				ai = code[i];
				wi = factor[i];
				sum += ai * wi;
			}
			var last = parity[sum % 11];
			if (parity[sum % 11] != code[17]) {
				tip = "校验位错误";
				pass = false;
			}
		}
	}
	// if(!pass) alert(tip);
	return pass;
}

/**
 * 将str转为时间类型
 * 
 * @param strDate
 * @returns {Date} add by xl
 */
function getDateForStringDate(strDate) {
	// 切割年月日与时分秒称为数组
	var s = strDate.split(" ");
	var s1 = s[0].split("-");
	var s2 = s[1].split(":");
	if (s2.length == 2) {
		s2.push("00");
	}
	return new Date(s1[0], s1[1] - 1, s1[2], s2[0], s2[1], s2[2]);
}

/**
 * 提示弹窗口 add by heqqiongqiong600
 */
function QexAlert(titleStr, messageStr) {
	return QEX.alert({
		title : titleStr,
		message : messageStr
	});
}

/**
 * 限制输入框不能输入中文 add by heqqiongqiong600
 */
function validChinese(id, msg) {
	var value = $("#" + id).val();
	if (/[^\x00-\xff]/g.test(value)) {
		$("#" + id).val("");
		QexAlert("提示", msg + "有中文字符，请重新输入");
	}
}

function postWin(URL, PARAMS) {
	var temp_form = document.createElement("form");
	temp_form.action = URL;
	temp_form.target = "_blank";
	temp_form.method = "post";
	temp_form.style.display = "none";
	for ( var x in PARAMS) {
		var opt = document.createElement("textarea");
		opt.name = x;
		opt.value = PARAMS[x];
		temp_form.appendChild(opt);
	}
	document.body.appendChild(temp_form);
	temp_form.submit();
}

/*******************************************************************************
 * @title formatterLengthContrl
 * @description 表格显示时字段过长，字符截取函数
 * @author HEQIONGQIONG420
 * @date 2016-08-17
 * @param value
 * @param rec
 * @param length
 * @returns
 */
function formatterLengthContrl(value, rec, length) {
	if (vaildNotNull(value)) {
		var strLength = value.length;
		if (strLength > length) {
			var substr = value.substr(0, length);
			return "<span  title='" + value + "'>" + substr + "...</span>";

		} else {
			return value;
		}
	}
}

/**
 * 把json数据加载到表单 同 方法setJson2Form add by qinweisheng431 2016-08-23
 */
$.fn.loadJson2Form = function(data) {
	return this.each(function() {
		var input, name;
		if (data == null) {
			this.reset();
			return;
		}
		for (var i = 0; i < this.length; i++) {
			input = this.elements[i];
			// checkbox的name可能是name[]数组形式
			name = (input.type == "checkbox") ? input.name.replace(/(.+)\[\]$/, "$1") : input.name;
			if (data[name] == undefined)
				continue;
			switch (input.type) {
			case "checkbox":
				if (data[name] == "") {
					input.checked = false;
				} else {
					// 数组查找元素
					if (data[name].indexOf(input.value) > -1) {
						input.checked = true;
					} else {
						input.checked = false;
					}
				}
				break;
			case "radio":
				if (data[name] == "") {
					input.checked = false;
				} else if (input.value == data[name]) {
					input.checked = true;
				}
				break;
			case "button":
				break;
			default:
				input.value = data[name];
			}
		}
	});
};

/**
 * 格式化json格式的时间 json to String add by qinweisheng431 2016-08-23
 */
function JsonTime2String(timeStamp) {
	var datetime = new Date();
	datetime.setTime(timeStamp);
	var year = datetime.getFullYear();
	// 月份重0开始，所以要加1，当小于10月时，为了显示2位的月份，所以补0
	var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
	var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
	var hour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
	var minute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
	var second = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
	return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
}

/**
 * @description 异步请求
 * @param data
 * @param callback
 * @param ajaxConfig
 * @returns
 */
function ajaxAsync(data, callback, ajaxConfig) {
	if (checkTimeOut() == 'timeout') {
		QEX.confirm({
			title : "提示",
			message : "登录超时，请重新登录！"
		}).on(function(r) {
			if (r) {
				window.location.href = casUrl + '/logout?service=' + newUrl;
			}
		});
		return false;
	}
	if (data == null || data == 'undefined' || data == "") {
		return createAjaxFail("错误的请求参数");
	}
	var jsonData = JSON.stringify(data);

	var defaultConfig = {
		type : "POST",
		async : true,
		url : baseUrl + "driverAction.do",
		data : jsonData,
		dataType : "json",
		success : function(result) {
			callback(null, result);
		},
		error : function(result) {
			createAjaxFail("执行异常，请联系管理员");
			callback('error', result);
		}
	};
	var ajaxConfig = ajaxConfig || {};
	var config = $.extend({}, defaultConfig, ajaxConfig);
	$.ajax(config);
}

/**
 * @description remote异步请求
 * @param data
 * @param callback
 * @param ajaxConfig
 * @returns
 */
function remoteAjaxAsync(data, callback, ajaxConfig) {

	if (checkTimeOut() == 'timeout') {
		QEX.confirm({
			title : "提示",
			message : "登录超时，请重新登录！"
		}).on(function(r) {
			if (r) {
				window.location.href = casUrl + '/logout?service=' + newUrl;
			}
		});
		return false;
	}

	if (data == null || data == 'undefined' || data == "") {
		return createAjaxFail("错误的请求参数");
	}
	data.remoteServiceId = data.serviceId;
	data.serviceId = "remoteService";
	var jsonData = JSON.stringify(data);
	var defaultConfig = {
		type : "POST",
		async : true,
		url : baseUrl + "driverAction.do",
		data : jsonData,
		dataType : "json",
		success : function(result) {
			callback(null, result);
		},
		error : function(result) {
			createAjaxFail("执行异常，请联系管理员");
			callback('error', result);
		}
	};
	var ajaxConfig = ajaxConfig || {};
	var config = $.extend({}, defaultConfig, ajaxConfig);
	$.ajax(config);
}

function getWebJson(serviceid, data) {

	data.serviceId = serviceid;
	return $.ajax({
		type : "POST",
		async : true,
		url : baseUrl + "driverAction.do",
		data : JSON.stringify(data),
		dataType : "json"
	});
}

function getMmJson(serviceid, data) {

	data.serviceId = "remoteService";
	data.remoteServiceId = serviceid;
	return $.ajax({
		type : "POST",
		async : true,
		url : baseUrl + "driverAction.do",
		data : JSON.stringify(data),
		dataType : "json"
	});
}

function getAreaNameByCode2(areaCode) {

	if (areaCode) {
		return getWebJson("paAreaService", {
			flag : "02",
			areaCode : areaCode
		});
	}

	return $.Deferred().reject(false);
}

function getCityNameByOrgAreaCode2(orgAreaCode) {

	if (orgAreaCode) {
		return getMmJson("070011", {
			'findType' : "B",
			'cityType' : "2",
			'oraAreaCode' : orgAreaCode
		});
	}
	return $.Deferred().reject(false);
}

// 将对象List中对象的值放入数组返回
function getObjValList(objectList) {
	var valList = [];// 会员类型数组
	objectList.each(function() {
		valList.push($(this).val());
	});
	return valList;
}

// 参数json对象化
function deltPara(paraType, parentParaCode) {
	var obj = {};
	obj.paraType = paraType;
	obj.parentParaCode = parentParaCode;
	return obj;
}

// 通过参数对象数组批量获取参数List
function getParasList(parentparas) {
	var reqData = new Object();// 创建传递对象
	reqData.serviceId = "mpParameterService";// 调用的Service对象
	reqData.flag = "14";// 执行方法表示
	reqData.dataList = [];
	for (var i = 0; i < parentparas.length; i++) {
		reqData = addReqData(reqData, i, parentparas[i].paraType, parentparas[i].parentParaCode);
	}
	return AjaxJsonAsync(reqData);
}

// 给参数集合添加参数
function addReqData(reqData, i, paraType, paraCode) {
	reqData.dataList[i] = {};
	reqData.dataList[i].paraType = paraType;
	reqData.dataList[i].parentParaCode = paraCode;
	return reqData;
}

// 去左右空格
function ltrim(s) {
	return (s == null ? "" : s).replace(/(^\s*)/g, "");
}

// 去右空格
function rtrim(s) {
	return (s == null ? "" : s).replace(/(\s*$)/g, "");
}

// 去左右空格
function trim(s) {
	return (s == null ? "" : s).replace(/(^\s*)|(\s*$)/g, "");
}

/**
 * 按指定格式，格式化
 * 
 * @param obj
 *            dom对象
 * @param pattern
 *            指定格式，如：10000
 * @author RANMENGLONG158
 * @date 2016-11-30 09:13:00
 */
var _idSuffix = Math.round(Math.random() * 10);// 1-10之间的随机整数，防止多个页面嵌套，中文只显示在第一个div下
function formatAmountSetValueByPattern(obj, pattern) {
	var value = $(obj).val().replace(/,/g, "");
	value = Number(value).toFixed(2).toString();
	if (pattern) {
		$(obj).val(datagridFormatNumberByPattern(value / pattern, pattern));// 格式化为指定格式的值
	} else {
		$(obj).val(datagridFormatNumber(value));
	}
	var chn = chineseNumber(value);
	if (!isSpace(chn)) {
		$(obj).parent().append('<div class="span_phone_code" id=' + obj.attr("id") + _idSuffix + '></div>');
		var $item = $("#" + obj.attr("id") + _idSuffix);
		// 不刷新页面，多次加载，出现多个中文显示div时，需要将其它的都删除
		$item.siblings().each(function() {
			if (this.tagName == 'DIV') {
				$(this).remove();
			}
		});
		$item.text(chn);
		$item.css({
			// 'width' : chn.length * 12,
			'margin-left' : $(obj).parent().find('.control-label').width(),
			'width' : '100%',
			'padding' : '0px 5px',
			'background' : '#fff3eb none no-repeat 10px center',
			'line-height' : '35px',
			'margin-top' : '10px',
			'text-align' : 'left',
			'font-size' : '12px',
			'display' : 'block'
		});
	} else {
		var $item = $("#" + obj.attr("id") + _idSuffix);
		$item.css({
			'display' : 'none'
		});
	}
}

/**
 * 把json数据加载到详情表单
 * @LIZAI937
 */
$.fn.loadJson2DetailForm = function(form,data) {
	return this.each(function() {
		var input, id;
		if (data == null) {
			this.reset();
			return;
		}
		var look = "#"+form+" label";
		for (var i = 0; i < $(look).length; i++) {
			input = $(look)[i];
			id = input.id;
			if (data[id] == undefined)
				continue;
			input.innerHTML = data[id];
		}
	});
};

/**
 * 数字转换为以 万 为单位
 * 
 * @param num
 * @param pattern
 *            格式，只能为10000（转为万元）或不传该值（为元）
 * @returns {String}
 */
function datagridFormatNumberByPattern(num, pattern) {
	num = num + "";
	if (num == null || num == '') {
		return "";
	}
	num = zeroFormat(num + "");// 去掉以0开头非个位数据
	if (isNaN(num) || num > Math.pow(10, 13)) {
		return "金额数据过大,最大限额拾万亿（拾兆）";
	}
	num = num.replace(new RegExp(/(,)/g), '');
	num = toNumber(num, pattern == 10000 ? '#,##0.0000000' : '');
	return num;
}
